package com.ingsing.user.controller;

import com.ingsing.user.common.enmus.ResultCode;
import com.ingsing.user.common.resp.Base;
import com.ingsing.user.common.resp.Resp;
import com.ingsing.user.common.utils.Md5Utils;
import com.ingsing.user.model.po.User;
import com.ingsing.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author: NALHOUG
 * @time: 2019/10/31 15:49
 * @explain:
 */
@Slf4j
@RestController
@RequestMapping(value = "/welcome")
public class LoginController {

    @Resource
    private IUserService userService;

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    private Resp login(@PathVariable User user, HttpServletRequest request) {
        log.info("后台获取的对象："+user);
        System.out.println("后台获取的对象："+user);
        Resp resp = new Resp();
        loginOption(user,resp,request);
        System.out.println(resp.getMsg());
        return resp;
    }

    private void loginOption(User user,Resp resp,HttpServletRequest request){
        User dbUser = null;
        String username = user.getUsername();
        String md5Password = Md5Utils.encrypt3Times(user.getPassword());
        //开始判断登录方式
        if (username.matches(Base.EMAIL_REGULAR)) {
            dbUser = userService.selectByEmail(username);
        }else if (username.matches(Base.PHONE_REGULAR)) {
            dbUser = userService.selectByPhone(username);
        }else {
            dbUser = userService.selectByUsername(username);
        }

        //判断用户是否存在
        if (null==dbUser){
            resp.setResultCode(ResultCode.ACCOUNT_NOT_EXIST);
            return;
        }
        //判断密码是否正确
        if (!md5Password.equals(dbUser.getPassword())){
            resp.setResultCode(ResultCode.LOGIN_PASSWORD_ERROR);
            System.out.println(user.getPassword()+dbUser.getPassword());
            System.out.println(md5Password);
            return;
        }
        //判断用户状态
        switch (dbUser.getIsDelete()){
            case 1:
                HttpSession session = request.getSession();
                //状态正常，存入session
                session.setAttribute(Base.ROLE_USER, dbUser);
                //刷新当前登录时间
                userService.setLastLogin(dbUser.getUserId());
                resp.setResultCode(ResultCode.LOGIN_SUCCESS);
                break;
            case 2:
                resp.setResultCode(ResultCode.ACCOUNT_OFF);
                break;
            case 0:
                resp.setResultCode(ResultCode.ACCOUNT_FORBIDDEN);
                break;
            default:
                resp.setResultCode(ResultCode.ACCOUNT_EXCEPTION);
                break;

        }
    }
}
